package com.ruoyi.wechat.service;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.ruoyi.common.exception.GlobalException;
import io.minio.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class IQRService {
    @Resource
    QrConfig qrconig;
    private  final    String endpointUrl="http://47.121.25.166:9000";
    private final String accessKey="admin";
    private final String secreKey="admin123456";
    private final String bucketName="qr-code";


    public String generateFile(String content)  {
        //content 是需要放到二维码的内容
        //生成到本地文件
        MinioClient minioClient = MinioClient.builder().endpoint(endpointUrl)
                .credentials(accessKey,secreKey).build();
        try {
            boolean b = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!b) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            } else {
                System.out.println("Bucket 'new-camping' already exists.");
            }
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            QrCodeUtil.generate(content, qrconig, "jpg", outputStream);
            InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            //文件名
            String fileName = new SimpleDateFormat("yyyyMMdd")
                    .format(new Date()) + "/" + UUID.randomUUID().toString()
                    .replace("-", "") + ".jpg";
            PutObjectArgs putObjectArgs = PutObjectArgs.builder().bucket(bucketName).bucket(bucketName)
                    .stream(inputStream, inputStream.available(), -1)
                    .object(fileName).build();
            //弄到minio
            minioClient.putObject(putObjectArgs);
            //访问的路径
            String url = endpointUrl + "/" + bucketName + "/" + fileName;
            return url;
        }catch (Exception e){
            throw new GlobalException("生成二维码错误");
        }
    }

    //输出到流
    public void generateStream(String content, HttpServletResponse response) throws IOException {
        //生成图片二维码 扫一下
        QrCodeUtil.generate(content, qrconig, "png", response.getOutputStream());
    }
}
